const express = require('express');
const router = express.Router();
const query = require('../conn/conn')
const fs = require('fs');
const path = require('path');
const crypto = require('crypto')
const http = require('http')
const jwt = require('jsonwebtoken');
const querystring = require('querystring')
 
const md5 = crypto.createHash('md5')
const { send } = require('process');

/* GET home page. */
// router.get('/', function(req, res, next) {
//   res.render('index', { title: 'Express' });
// });

router.get('/getlogin', async (req, res, next)=>{
    // let resaaaa= await query("SELECT * FROM user")
    // res.send(resaaaa);

    let reslut=await query(`SELECT * FROM user WHERE username='${req.query.username}' and password='${req.query.password}'`);
    // let aaaaaa={...req.query};
    if(reslut.length){
        const userInfo = {
            userName:req.query.username,
            loginTime:Date.now()
        }
        // res.send({msg:'账号密码正确',code:'0'});
        let token = 'Bearer '+jwt.sign(userInfo,'gege3326',{expiresIn:60*60*24});
        return res.send({
            msg:'登陆成功',
            code:0,
            token
        });
    }

        return res.send({msg:'登录失败',code:'1'})
})
router.get('/getsms', async (req, res, next)=>{
    // let resaaaa= await query("SELECT * FROM user")
    // res.send(resaaaa);
    let code=getCode();
    fs.writeFile(path.join(__dirname, '..','public','temp',(req.query.phone)),code,'utf8',(err)=>{
        if(err){
            console.log(err);
        }else{
            send_sms('api.smsbao.com','809739979','daifancheng',`[千峰2107]您的验证码为：${code}`,req.query.phone)
            
            // res.send({msg:'发送成功',msgcode:0});
        }
        
    })
    
    function send_sms(smsapi,user,password,content,phone){
        var pass = md5.update(password).digest('hex')
        var data={  
            'u':user,  
            'p':pass,
            'm':phone,
            'c':content
        }
        var content=querystring.stringify(data);
        var sendmsg='';
        var options={  
            hostname:smsapi,   
            path:'/sms?'+content,  
            method:'GET'  
        } 
     
        var req=http.request(options,function(res){  
            res.setEncoding('utf-8');  
            res.on('data',function(result){
                statusStr(result)
                // return(result)
            });  
            res.on('end',function(){
            });  
        });  
        req.on('error',function(err){  
            console.error(err);  
        });  
        req.end();  
    }
     
    function statusStr(result){
        switch(result)
        {
            case '0':
                console.log('短信发送成功')
                res.send({msg:'短信发送成功',code:'0'})
                break
            case '-1':
                console.log('参数不全')
                res.send({msg:'参数不全',code:'-1'})
                break
            case '-2':
                console.log('')
                res.send({msg:'服务器空间不支持,请确认支持curl或者fsocket，联系您的空间商解决或者更换空间！',code:'-2'})
                break
            case '30':
                console.log('密码错误')
                res.send({msg:'密码错误',code:'30'})
                break
            case '40':
                console.log('账户不存在')
                res.send({msg:'账户不存在',code:'40'})
                break
            case '41':
                console.log('余额不足')
                res.send({msg:'余额不足',code:'41'})
                break
            case '42':
                console.log('账户已过期')
                res.send({msg:'账户已过期',code:'42'})
                break
            case '43':
                console.log('IP地址限制')
                res.send({msg:'IP地址限制',code:'43'})
                break
            case '50':
                console.log('内容含有敏感字')
                res.send({msg:'内容含有敏感词',code:'50'})
                break
        }
    }
    function random(min, max) {
        return Math.ceil(Math.random() * (max - min + 1) + min - 1);
    }
    function getCode() {
        
        var code = '';
        var type;
        for (var i = 0; i < 6; i++) {
            type = random(1, 3);
            switch (type) {
                case 1:
                    code += String.fromCharCode(random(48, 57));
                    break;
                case 2:
                    code += String.fromCharCode(random(48, 57));
                    break;
                case 3:
                    code += String.fromCharCode(random(48, 57));
                    break;
            }
        }
        return code;
    }
})
router.get('/verify', async (req, res, next)=>{
    fs.readFile(path.join(__dirname, '..','public','temp',req.query.phone),'utf8',(err,data)=>{
        if(err){
            console.log(err );
            res.send({msg:'提交手机号与验证手机号不符合',msgcode:1})
        }else if(req.query.yzmval==data){
            let name=req.query.phone;
            let pass=req.query.password;
            new Promise(async function(resolve, reject){
                let resu=await query(`select * from user where phone='${name}'`);
                if(resu.length){
                    reject();
                }else{
                    resolve();
                }
            }).then(()=>{
                let resss= query(`INSERT INTO user (username, password, phone) VALUES ('${req.query.username}','${req.query.password}','${req.query.phone}')`);
                res.send({msg:'注册成功',code:0})
            }).catch(()=>{
                res.send({msg:'注册失败,用户名已存在',code:3})
            })
            fs.unlink(path.join(__dirname, '..','public','temp',req.query.phone),async (err)=>{
                if(err) console.log(err )
                console.log('文件删除成功')
            })
            console.log(req.query.username);
            
        }else if(req.query.code!=data){
            res.send({msg:'验证码不正确',code:2})
        }
    })
})







module.exports = router;
